/**
 * Created by wang on 17-6-16.
 */
var fs = require("fs");
var rd = require("rd");


var url = './host';
var lastHostArr = [];
var HOSTNAME = [];
var hostObjectARR = [];


main(url);


function main(url) {
    getApkName(url);
}


function getApkName(url) {
    rd.eachFileFilterSync(url, function (f, s) {
        HOSTNAME.push(f);
    });
    getHost(HOSTNAME);

}


function getHost(apkName) {
    var length = apkName.length;
    for (var i = 0; i < length; i++) {
        var hosts = fs.readFileSync(apkName[i]).toString();
        var host = hosts.split(/[\n\r]/);
        for (var j = 0; j < host.length; j++) {
            if (host[j] != "") {
                getLastHostArr(host[j])
            }
        }
    }

    getHostArr(lastHostArr);
}

function getLastHostArr(host) {
    if (host.substring(0, 6) == "Host: ") {
        var str = host.substring(6);
        lastHostArr.push(str)
    }
}

function getHostArr(arr) {

    for (var j = 0; j < arr.length; j++) {
        var hostObject = {};
        hostObject.host = arr[j];

        if (hostObjectARR.length == 0) {
            hostObject.count = 1;
            hostObjectARR.push(hostObject)
        } else {
            hostObject.count = 0;
            hostCount(hostObject);
        }
    }
    console.log(hostObjectARR.sort(compareNumbers))
}

function hostCount(hostObject){
    for (var i = 0; i < hostObjectARR.length; i++) {
        if (hostObjectARR[i].host == hostObject.host) {
            hostObjectARR[i].count += 1;
            break;
        } else if (i == hostObjectARR.length - 1) {
            hostObjectARR.push(hostObject)
        }
    }
}

function compareNumbers(a, b) {
    return b.count - a.count;
}
